package com.isunland.managesystem.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.isunland.managesystem.R;
import com.isunland.managesystem.entity.MaterielLomContent;
import com.isunland.managesystem.ui.MaterielDialogFragment;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.NumberUtil;
import com.isunland.managesystem.utils.ToastUtil;

public abstract class BaseMaterielDetailFragment extends BaseFragment implements OnClickListener {

  protected static final int CHOOSE_MATERIE = 0;
  protected static final int DETAIL_MATERIEL = 1;
  protected static final int DELETE_MATERIEL = 2;
  protected static final int SAVE_MATERIEL = 3;
  protected static final int CHOOSE_CATEGORY = 4;

  //物料类别
  protected TextView tvMaterielCategory;
  protected ImageView ibMaterielCategory;

  protected TextView tvMaterielName;
  protected ImageView ibMaterielName;
  protected TextView tvMaterielCode;
  protected TextView tvMaterielSelfCode;
  protected TextView tvMaterielType;//规格型号
  protected TextView tvBaseApartment;//基本单位
  protected EditText tvUnitPrice;//单价
  protected EditText etNumber;//数量
  protected EditText etallPrice;//总额
  protected EditText etNotes;//备注
  //	protected LinearLayout llmaterialGone;//入库批次。生产日期。有效期
  //	protected TextView tvbatchstorage;//入库批次
  //	protected TextView tvProductiondate;//生产日期
  //	protected TextView tvValidityperiod;//有效期
  protected MaterielLomContent content = new MaterielLomContent();//选择物料dialog返回的值
  //protected double stockNumber=0.0;//库存数量
  protected String customerId = "";//客户单位id
  protected String storageId = "";//仓库id
  protected String mainMaterialCode = "";//主表物料类别
  protected String kindId = "";//物料类别id
  protected String kindName = "";//物料类别name
  private TextWatcher textWatcher = new TextWatcher() {

    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
      try {
        LogUtil.i("onTextChanged==" + etNumber.getText().toString());
        Double n;
        Double p;
        if (TextUtils.isEmpty(etNumber.getText().toString())) {
          n = 0.0;
        } else {
          n = Double.parseDouble(etNumber.getText().toString());
        }
        if (TextUtils.isEmpty(tvUnitPrice.getText().toString())) {
          p = 0.0;
        } else {
          p = Double.parseDouble(tvUnitPrice.getText().toString());
        }
        if ((n * p) > 100000000) {
          etallPrice.setText("100000000");
        } else {
          etallPrice.setText(NumberUtil.numberBigToString(n * p));
        }
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
    }

    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      LogUtil.i("beforeTextChanged==" + etNumber.getText().toString());
    }

    @Override public void afterTextChanged(Editable s) {
      LogUtil.i("beforeTextChanged==" + etNumber.getText().toString());
    }
  };

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle();
  }

  /**
   * 设置标题
   */
  protected abstract void setTitle();

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_materiel_detail, container, false);
    //物料类别
    tvMaterielCategory = (TextView) v.findViewById(R.id.tv_materiel_category);

    tvMaterielName = (TextView) v.findViewById(R.id.tv_materiel_name);
    tvMaterielCode = (TextView) v.findViewById(R.id.tv_materiel_code);
    tvMaterielSelfCode = (TextView) v.findViewById(R.id.tv_materiel_self_code);
    tvMaterielType = (TextView) v.findViewById(R.id.tv_product_type);
    tvBaseApartment = (TextView) v.findViewById(R.id.tv_base_apartment);
    tvUnitPrice = (EditText) v.findViewById(R.id.et_unit_price);
    etNumber = (EditText) v.findViewById(R.id.et_number);
    etNotes = (EditText) v.findViewById(R.id.et_notes);
    //总金额
    etallPrice = (EditText) v.findViewById(R.id.et_all_price);

    //		llmaterialGone=(LinearLayout) v.findViewById(R.id.ll_material_gone);
    //		tvbatchstorage=(TextView) v.findViewById(R.id.tv_batch_storage);
    //		tvProductiondate=(TextView) v.findViewById(R.id.tv_production_date);
    //		tvValidityperiod=(TextView) v.findViewById(R.id.tv_validity_period);

    ibMaterielCategory = (ImageView) v.findViewById(R.id.ib_materiel_category);
    ibMaterielName = (ImageView) v.findViewById(R.id.ib_materiel_name);

    ibMaterielName.setOnClickListener(this);
    ibMaterielCategory.setOnClickListener(this);

    //监听文字改变
    etNumber.addTextChangedListener(textWatcher);
    tvUnitPrice.addTextChangedListener(textWatcher);

    initMaterialData();
    return v;
  }

  /**
   * 初始化控件
   */
  protected abstract void initMaterialData();

  @Override public void onClick(View v) {
    switch (v.getId()) {
      //选择物料的dialog
      case R.id.ib_materiel_name:
        if (TextUtils.isEmpty(tvMaterielCategory.getText().toString())) {
          ToastUtil.show(R.string.choose_kind);
        } else {
          showDialog(CHOOSE_MATERIE);
        }

        break;
      //选择物料类别
      case R.id.ib_materiel_category:

        showDialog(CHOOSE_CATEGORY);

        break;

      default:
        break;
    }
  }

  @SuppressWarnings("static-access") protected void showDialog(int requestCode) {

    DialogFragment dialog = null;
    switch (requestCode) {

      //选择物料类别
      case CHOOSE_CATEGORY:
        dialog = new MaterielDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", MaterielDialogFragment.type_catragory);
        bundle.putSerializable("customerId", customerId);
        bundle.putSerializable("storageId", storageId);
        bundle.putSerializable("kindId", mainMaterialCode);
        dialog.setArguments(bundle);
        break;
      //选择物料名称
      case CHOOSE_MATERIE:

        dialog = new MaterielDialogFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("type", MaterielDialogFragment.type_materiel);
        bundle2.putSerializable("customerId", customerId);
        bundle2.putSerializable("storageId", storageId);
        bundle2.putSerializable("kindId", kindId);
        dialog.setArguments(bundle2);

        break;

      case DELETE_MATERIEL:
        dialog = new BaseRestartDialogFragment().newInstance(R.string.deleteConfirm,
            R.string.restart_title);
        break;

      case SAVE_MATERIEL:
        dialog =
            new BaseRestartDialogFragment().newInstance(R.string.ifSave, R.string.restart_title);
        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog == null) return;
    dialog.setTargetFragment(BaseMaterielDetailFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHOOSE_MATERIE) {

      content = (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      tvMaterielName.setText(content.getName());
      tvMaterielCode.setText(content.getCustomAttrs());
      tvMaterielSelfCode.setText(content.getFlag());
      tvMaterielType.setText(content.getExtParam());//规格型号
      tvBaseApartment.setText(content.getExtParam2());//基本单位
      //如果返回的单价为空可编辑，不为空就不可编辑
      if (!TextUtils.isEmpty(content.getExtParam4())) {
        tvUnitPrice.setEnabled(false);
      } else {
        tvUnitPrice.setEnabled(true);
      }
      tvUnitPrice.setText(content.getExtParam4());//单价
      //			stockNumber=Double.parseDouble(content.getExtParam3().toString());
      //			etNumber.setText((int)stockNumber+"");//库存数量

    }
    if (requestCode == CHOOSE_CATEGORY) {

      content = (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      tvMaterielCategory.setText(content.getName());
      kindId = content.getId();
      kindName = content.getName();

      //如果重新选择物料类别
      tvMaterielName.setText("");
      tvMaterielCode.setText("");
      tvMaterielSelfCode.setText("");
      tvMaterielType.setText("");//规格型号
      tvBaseApartment.setText("");//基本单位
      tvUnitPrice.setText("");//单价
      etNumber.setText("");//库存数量
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
}
